﻿using System;
using System.Linq;
using UnityEngine;

namespace Core.Extension.ObservableValue
{
    /// <summary>
    /// 可观察值。只支持int float string double等
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Observable<T>
    {
        private Action<T> _onValueChanged;
        private T _value;

        public T Value
        {
            get => _value;
            set
            {
                if (_value != null && !_value.Equals(value))
                {
                    _onValueChanged?.Invoke(value);
                }

                _value = value;
            }
        }

        public Observable(T normalValue)
        {
            _value = normalValue;
        }

        public Observable()
        {
        }


        /// <summary>
        /// 添加监听
        /// </summary>
        /// <param name="action">在Value发生改变时触发</param>
        /// <param name="bindObj">监听所绑定的对象，当对象Destroy时，监听自动移除</param>
        public void AddListener(Action<T> action, GameObject bindObj = null)
        {
            if (_onValueChanged == null ||
                !_onValueChanged.GetInvocationList().Contains(action))
            {
                _onValueChanged += action;
                if (bindObj != null)
                {
                    bindObj.OnDestroy(delegate { RemoveListener(action); });
                }
            }
        }


        /// <summary>
        /// 移除某个监听委托
        /// </summary>
        /// <param name="action"></param>
        public void RemoveListener(Action<T> action)
        {
            if (_onValueChanged != null)
            {
                _onValueChanged -= action;
            }
        }

        /// <summary>
        /// 移除所有监听
        /// </summary>
        public void RemoveAllListeners()
        {
            _onValueChanged = null;
        }
    }
}